package com.orangelife.mobile.app.service;

import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RemoteViews;
import com.common.sp.AppSp;
import com.common.sp.CommSp2;
import com.common.sp.OtherSp;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.SystemInfoUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.common.view.NewConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.download.FileDownloader;
import com.orangelife.mobile.login.activity.SplashADActivity;
import com.orangelife.mobile.util.CleanCacheUtils;
import com.orangelife.mobile.util.NumberProgressBar;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.json.JSONObject;



/**
 * 后台服务下载闪屏广告图片,检查app更新
 * Created by HeYuCan on 2016/8/11.
 */
public class MyService extends Service {
    public static final String TAG = "MyService";
    public static final String Install_Apk = "Install_Apk";
    /********
     * download progress step
     *********/
    private static final int down_step_custom = 3;

    private static final int TIMEOUT = 10 * 1000;// 超时
    private static String down_url;
    private static final int DOWN_OK = 1;
    private static final int DOWN_ERROR = 0;
    private String app_name = "橙子生活";
    private NotificationManager notificationManager;
    private Notification notification;
    private Intent updateIntent;
    private PendingIntent pendingIntent;
    private RemoteViews contentView;

    // 1为闪屏页的调用, 2为主页的调用
    private int mFromWhere = 0;

    private MyBinder mBinder = new MyBinder();

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 被销毁时启动自身，保持自身在后台存活
        startService(new Intent(MyService.this, MyService.class));
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }


    public class MyBinder extends Binder {
        private String updateSize;
        private String updateInfo;
        private String newVersion;
        private String isForce;
        private Context context;
        private static final int REFRESH_PROGRESS = 3;

        public void loadADImage() {

            VolleyHttpUtil.getInstance().getWithCallback(Constant.URL_ADVERTISMENT, new VolleyHttpUtil.ResponseCallBack() {
                @Override
                public void handleResponse(JSONObject jsonObject, int i) {
                    List<Map<String, Object>> adInfoList = null;

                    String s = CommSp2.getCommID();
                    String info = OtherSp.getAdImgInfo(s);

                    if (OrangeErrorHandler.getInstance().isSuccess(jsonObject, false)) {
                        adInfoList = OrangeDataHandler.getListFromJsonWithPageEntity(
                            jsonObject, new TypeToken<List<Map<String, Object>>>() {
                            }.getType(), null, null);
                    }
                    if (adInfoList != null) {
                        if (adInfoList.size() == 0 && OtherSp.getIsSuccessLoadImg(s)) {
                            deleteOlderADImg();
                        }
                  else   if ( adInfoList.size() > 0) {//因为每次

                        img2Disk(adInfoList);

                        //                        OtherSp.putIsSuccessLoadImg(CommSp2.getCommID(),true);
                    } else  {//只有当今天该小区广告下载失败,且今天已经的广告也下载失败时才设为false,不然今天下载失败而昨天成功时若设false则连昨天的广告也无法读取
                        //                        OtherSp.putIsSuccessLoadImg(CommSp2.getCommID(),false);
                    }
                }
                }
            });

        }

        private void deleteOlderADImg(){
            String s = OtherSp.getAdImgInfo(CommSp2.getCommID());
            String imgInfo1[] = s.split("#");
            //String url = imgInfo1[0];
            String url = imgInfo1[1];
            File preFile = ImageLoader.getInstance().getDiskCache().get(url);
            if ( preFile != null) {
                preFile.delete();
                OtherSp.putAdImgInfo(CommSp2.getCommID(),"");
                OtherSp.putIsSuccessLoadImg(CommSp2.getCommID(), false);
            }
        }


        public void img2Disk(List list) {
            String s = OtherSp.getAdImgInfo(CommSp2.getCommID());

            String imgInfo1[] = s.split("#");
            String url="";
            if(imgInfo1.length>1) {
                url = imgInfo1[1];
            }
            Map<String, Object> map = (Map) list.get(0);

        /*广告图片*/
            String pics = String.valueOf(map.get("pics"));
            String adPageUrl = String.valueOf(map.get("url"));
        /*showTime*/
            String showTime = String.valueOf(map.get("showTime"));
            String title=String.valueOf(map.get("title"));
            if (pics.equals(url)) {
                return;
            }

            StringBuilder imgInfo = new StringBuilder();
            //将图片对应的跳转url和展示时间合一起,储存方便

            ImageLoader.getInstance().loadImage(pics, null);
            File preFile = ImageLoader.getInstance().getDiskCache().get(url);
            File file = ImageLoader.getInstance().getDiskCache().get(pics);
            //若今天的图片下载成功则删除之前下载的该小区图片
            if (file != null && preFile != null) {
                preFile.delete();
            }
            imgInfo.append("#").append(pics).append("#")
                    .append(adPageUrl).append("#")
                    .append(showTime).append("#").append(title);
            OtherSp.putAdImgInfo(CommSp2.getCommID(), imgInfo.toString());
            OtherSp.putIsSuccessLoadImg(CommSp2.getCommID(), true);
            OtherSp.putAdImgTitle(title);

        }


        public void createNotification() {
//            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notification = new Notification(R.mipmap.ic_launcher, app_name + ":正在下载更新", System.currentTimeMillis());
//
            /*** 自定义  Notification 的显示****/
            contentView = new RemoteViews(getPackageName(), R.layout.notification_item);
            contentView.setTextViewText(R.id.notificationTitle, app_name + ":正在下载更新");
            contentView.setTextViewText(R.id.notificationPercent, "0%");
            contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);
            notification.contentView = contentView;

            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(R.layout.notification_item, notification);
        }


        /*********
         * update UI
         ******/
        private final Handler handler = new Handler() {
            @Override

            public void handleMessage(Message msg) {
                notification.flags = Notification.FLAG_AUTO_CANCEL;
                switch (msg.what) {


                    case DOWN_OK:
                        if(dialog!=null) {
                            dialog.dismiss();
                        }
                        contentView.setTextViewText(R.id.notificationTitle, app_name + "橙子生活，下载完成！");
                        notification.flags = Notification.FLAG_AUTO_CANCEL;
                        notification.contentView = contentView;
                        notificationManager.notify(R.layout.notification_item, notification);
                      if(!isForce.equals("0")) {
                          if (context != null) {
                              if (!((Activity) context).isFinishing()) {
                                  final NewConfirmDialog newConfirmDialog =
                                      new NewConfirmDialog(context, "更新完成",
                                          getResources().getString(R.string.update_done), "确定");
                                  newConfirmDialog.setCancelable(false);
                                  NewConfirmDialog.ClickListenerInterface listener =
                                      new NewConfirmDialog.ClickListenerInterface() {
                                          @Override
                                          public void doLeft() {

                                          }

                                          @Override
                                          public void doRight() {
                                              newConfirmDialog.dismiss();
                                              installApk();
                                          }
                                      };
                                  newConfirmDialog.setClicklistener(listener);
                                  handler.post(new Runnable() {
                                      @Override
                                      public void run() {
                                          newConfirmDialog.show();
                                      }
                                  });
                              }
                          }else {
                              installApk();
                          }
                      }else {
                            installApk();
                        }
                        break;

                    case DOWN_ERROR:
                        contentView.setTextViewText(R.id.notificationTitle, app_name + ":下载失败");
                        notification.flags = Notification.FLAG_AUTO_CANCEL;
                        notification.contentView = contentView;
                        notificationManager.notify(R.layout.notification_item, notification);
                        if(dialog!=null) {
                            dialog.dismiss();
                        }
                        ToastHelper.getInstance()._toast("下载失败，请稍后重试");
                        AppSp.setHasNewVersion(true);
                        Constant.FIRST_OPEN = "0";
                        CurryApplication.getInstance().setUpdate(true);

//                        ((SplashADActivity) context).showAndJump();
                        if (mFromWhere == 1) {
                            CurryApplication.getInstance().exit();
                        }
                        break;

//                    case REFRESH_PROGRESS:
//                        int updateCount=msg.arg1;
//                        progressBar.setProgress(updateCount);
//                        break;


                    default:

                        break;
                }
            }
        };

        private void installApk() {
            File file = new File(saveFileName);
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);

            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            MyService.this.startActivity(intent);
            AppSp.setVersionInfo(updateInfo);
            AppSp.setHasNewVersion(false);
            if (mFromWhere == 1) {
                CurryApplication.getInstance().exit();
            }
        }


        public String apkUrl;
        /* 下载包安装路径 */
        private String savePath = Environment.getExternalStorageDirectory().getPath()+"/OrangeLife/";

        private String saveFileName = savePath + "orangelife.apk";

        /**
         *
         * @param fromWhere 1说明该方法被闪屏页调用,2为主页调用,3为设置页面调用
         */
        public void check(int fromWhere, Context context, String s, String newVersion, String minVersion, String url, String versionInfo, boolean isToast) {
            this.context = context;
            this.newVersion=newVersion;
            String currentVer = SystemInfoUtil.getVersionName(MyService.this);
//            currentVer="3.1.0";
            isForce = s;
            if (isNew(minVersion, currentVer)) {/*如果大于最低使用版本，则强制更新*/
                isForce = "1";
                CleanCacheUtils.getInstance().init(MyService.this);
                CleanCacheUtils.getInstance().cleanCache();
                checkUpdateInfo(fromWhere, url, isForce, versionInfo, newVersion);
            } else if (isNew(newVersion, currentVer)) {
                checkUpdateInfo(fromWhere, url, isForce, versionInfo, newVersion);
            } else if (newVersion.equals(currentVer)) {
                if (fromWhere == 3 || isToast) {
                    ToastHelper.getInstance()._toast("当前已是最新版本！");
                    AppSp.setHasNewVersion(false);
                }
                if (fromWhere == 1) {
                    ((SplashADActivity) context).showAndJump();
//                if (AppSp.isShowUpdateInfo()) {
//                    //checkUpdateInfo(url, versionInfo, newVersion); 3.8 关闭 更新成功 再次进入显示更新信息
//                }
                }
            } else {
                if (fromWhere == 1) {
                    ((SplashADActivity) context).showAndJump();
                } else {
                    ToastHelper.getInstance()._toast("版本信息错误");  //当前版本高于服务端返回的最新版时会报这个错误..
                    AppSp.setHasNewVersion(false);
                    return;
                }
            }
        }

        public boolean isNew(String newVersion, String oldVersion) {
            Pattern pattern = Pattern.compile("^(([0-9]+)\\.)*(([0-9]+|[a-z]+))$");

            if (!pattern.matcher(newVersion).matches() || !pattern.matcher(oldVersion).matches()) {
                return false;
            }
            String[] newVer = newVersion.split("\\.");
            String[] oldVer = oldVersion.split("\\.");

            for (int i = 0; i < newVer.length; i++) {
                if (newVer[i].compareTo(oldVer[i]) > 0) {
                    return true;
                }
                if (newVer[i].compareTo(oldVer[i]) < 0) {
                    return false;
                }
                if (newVer.length > oldVer.length) {
                    return true;
                }
            }

            return false;

        }

        public void checkUpdateInfo(int fromWhere, String url, String isForce, String info, String title) {
            apkUrl = url;
            mFromWhere = fromWhere;
            if (isForce.equals("1")) {
                showNoticeDialog(1, info, title);
            } else if (isForce.equals("2")) {
                showNoticeDialog(2, info, title);
            } else if (mFromWhere == 1 && isForce.equals("0")) {  //闪屏页若弹出更新提示,则一定是强制更新
                ((SplashADActivity) context).showAndJump();
            } else {
                showNoticeDialog(0, info, title);
            }
        }


        private void showNoticeDialog(final int isForce, final String info, String title) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Looper.prepare();
                    updateInfo = info;
                    final NewConfirmDialog confirmDialog;

//                    String url = "http://gdown.baidu.com/data/wisegame/bd47bd249440eb5f/shenmiaotaowang2.apk";
                    updateSize = FileDownloader.getDownloadSize(apkUrl);

                    if (isForce == 1 || isForce == 2) {

                        confirmDialog = new NewConfirmDialog(updateSize, context, "发现新版本！("+newVersion+")", updateInfo, null, "下载更新");
                        confirmDialog.setCancelable(false);
                    } else {
                        confirmDialog = new NewConfirmDialog(updateSize, context, "发现新版本！("+newVersion+")", updateInfo, "取消", "下载更新");
                    }

                    NewConfirmDialog.ClickListenerInterface listener = new NewConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doLeft() {
                            confirmDialog.dismiss();
                            AppSp.setHasNewVersion(true);
                            if (mFromWhere == 1) {  //闪屏页更新必定是强制更新,无取消键,但防止服务端传错isForce
                                ((SplashADActivity) context).showAndJump();
                            }
                        }

                        @Override
                        public void doRight() {
                            confirmDialog.dismiss();
                            if (!android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())) {
                                ToastHelper.getInstance()._toast("请检查是否存在sd卡");
                                return;
                            }
                            createNotification();
                            if(isForce!=0) {
                                initProgressDialog();
                            }else{
                                ToastHelper.getInstance()._toast("正在后台下载最新版本，可在任务栏中查看进度。");
                            }
                            downloadAPK();
                        }
                    };

                    confirmDialog.setClicklistener(listener);
                    if (context != null) {
                        if (!((Activity) context).isFinishing()) {
                            confirmDialog.show();
                        }
                    }

                    Looper.loop();
                }
            }).start();

        }

        private NumberProgressBar progressBar;
//        private AlertDialog dialog;
        private Dialog dialog;
        private void initProgressDialog() {
            if (context != null) {
                if (!((Activity) context).isFinishing()) {
                    progressBar = new NumberProgressBar(context);
                    final LayoutInflater inflater = LayoutInflater.from(context);
                    View v = inflater.inflate(R.layout.progress, null);
                    progressBar = (NumberProgressBar) v.findViewById(R.id.numberbar);
                    progressBar.setMax(100);
                    dialog = new Dialog(context, R.style.NewUIAlertViewStyle);
                    dialog.setContentView(v);
                    dialog.setCancelable(false);
                    dialog.show();
                }
            }
        }
        private void notifyBar(int updateCount) {
            contentView.setTextViewText(R.id.notificationPercent, updateCount + "%");
            contentView.setProgressBar(R.id.notificationProgress, 100, updateCount, false);
            notification.contentView = contentView;
            notificationManager.notify(R.layout.notification_item, notification);

            if(!isForce.equals("0")) {
                progressBar.setProgress(updateCount);
            }
//            Message message=new Message();
//            message.arg1=updateCount;
//            message.what=REFRESH_PROGRESS;
//            handler.sendMessage(message);

        }

        public void setAppURL(String url){
            apkUrl=url;
        }

        public void setContext(Activity context){
            this.context=context;
        }


        public void functionUpdate(){
            //functionUpdate()会在CommonJs.updateAPK()中直接调用 故必须判断初始化
            if(contentView==null) {
                createNotification();
                if (progressBar == null) {
                    initProgressDialog();
                    downloadAPK();
                }
            }
            else {
                ToastHelper.getInstance()._toast("已在下载更新，您可在任务栏中查看进度。");
                ((Activity)context).finish();
                return;
            }
        }

        private void downloadAPK() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {

                        int down_step = down_step_custom;// 提示step
                        int downloadCount = 0;// 已经下载好的大小
                        int updateCount = 0;// 已经上传的文件大小
                        //apkUrl = "http://gdown.baidu.com/data/wisegame/bd47bd249440eb5f/shenmiaotaowang2.apk";
                        //apkUrl="https://www.com/downloads/orangelife/dome/down/OrangeLife.apk";
                        URL url = new URL(apkUrl);

                        HttpURLConnection conn = (HttpURLConnection) url
                                .openConnection();
                        conn.setRequestProperty("Accept-Encoding", "identity");
                        conn.connect();
                        int totalSize = conn.getContentLength();// 文件总大小
                        InputStream inputStream = conn.getInputStream();

                        File file = new File(savePath);
                        if (!file.exists()) {
                            file.mkdir();
                        }
                        String apkFile = saveFileName;
                        File ApkFile = new File(apkFile);
                        FileOutputStream outputStream = new FileOutputStream(ApkFile);

                        byte buffer[] = new byte[1024];
                        int readsize = 0;
                        while ((readsize = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, readsize);
                            downloadCount += readsize;// 时时获取下载到的大小
                            int hasLoaded = downloadCount * 100 / totalSize;
                            int fenmu = updateCount;
                            boolean iscontinue = hasLoaded >= fenmu;
                            /*** 每次增张3%**/
                            if (updateCount == 0 || hasLoaded - down_step >= updateCount) {
                                updateCount += down_step;
                                // 改变通知栏与弹出进度条
                                notifyBar(updateCount);
                            }
                        }

                        notifyBar(100);
                        outputStream.close();
                        inputStream.close();
                        if (downloadCount >= totalSize) {
                            Message message = new Message();
                            message.what = DOWN_OK;
                            handler.sendMessage(message);
                        }
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                        Message message = new Message();
                        message.what = DOWN_ERROR;
                        handler.sendMessage(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                        Message message = new Message();
                        message.what = DOWN_ERROR;
                        handler.sendMessage(message);
                    }
                }
            }).start();
        }


    }


}
